<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="btn-add">
        <el-button
        icon="el-icon-circle-plus-outline"
        type="button"
        class="el-button el-button--primary"
        @click="addInOrOut"
        >
            新增</el-button
        >
    </div>

    <!-- 新增数据弹窗 -->
    <el-dialog
      title="新增"
      :visible.sync="showAdd"
      @close="showAdd = false"
      width="50%"
    >
    <el-form :model="createForm" ref="createForm" :rules="addRules" label-width="100px">
        <el-row>
            <el-col :span="8">
                <el-form-item label="条码" prop="facilityBarcode" >
                    <el-input placeholder="请扫码或输入资源条码" v-model="createForm.facilityBarcode" autosize/>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="借/归人" prop="accessJobNumber" >
                    <!-- <el-input placeholder="请输入借出/归还人工号" v-model="createForm.accessJobNumber"/> -->
                    <el-select
                        @focus="focusName"
                        filterable
                        v-model="createForm.accessJobNumber">
                        <el-option
                        placeholder="请选择借/归人"
                            v-for="(item,index) in userList"
                            :key="index"
                            :label="item.userName"
                            :value="item.userName">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="借/归状态" prop="accessType">
                    <el-select
                        v-model="createForm.accessType"
                        >
                        <el-option
                        placeholder="请选择借出/归还"
                            v-for="(item,index) in accessTypeList"
                            :key="index"
                            :label="item"
                            :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="8">
                <el-form-item label="借/归日期" prop="accessDate">
                    <el-date-picker
                        v-model="createForm.accessDate"
                        type="datetime"
                        placeholder="选择日期时间"
                        align="right"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        >
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :span="16">
                <el-form-item label="借出位置" prop="lendingPosition">
                    <el-input placeholder="请输入借出位置；（如：整机三线、内部OBA、一楼充电桩线等）" clearable type="textarea" v-model="createForm.lendingPosition"/>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addfacility('createForm')"
            >新增</el-button
            >
        </div>
    </el-dialog>


    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->
        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.facilityBarcode) }"
            v-model="param.facilityBarcode"
            placeholder="资源条码"
        ></el-input>

        <el-select
            style="margin-right: 15px;width: 150px"
            v-model="param.facilityBarcodeType1"
            placeholder="资源大类"
            class="ul-item"
            filterable
            clearable
            @focus="getBarcodeType('大类')">
            <el-option
                v-for="(item,index) in barcodeType1List"
                :key="index"
                :label="item.facilityBarcodeName"
                :value="item.facilityBarcodeName">
            </el-option>
        </el-select>

        <el-select
            style="margin-right: 15px;width: 150px"
            v-model="param.facilityBarcodeType2"
            placeholder="资源小类"
            class="ul-item"
            filterable
            clearable
            @focus="getBarcodeType('小类')">
            <el-option
                v-for="(item,index) in barcodeType2List"
                :key="index"
                :label="item.facilityBarcodeName"
                :value="item.facilityBarcodeName">
            </el-option>
        </el-select>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px;width: 150px"
            v-model="param.accessJobNumber"
            placeholder="借/还人"
        ></el-input>

        <el-select
            clearable
            v-model="param.accessType"
            style="margin-right: 15px;width: 150px"
            placeholder="资源出入状态">
            <el-option
                v-for="(item,index) in accessTypeList"
                :key="index"
                :label="item"
                :value="item">
            </el-option>
        </el-select>
        
        <el-date-picker
          v-model="dateOptions"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          style="margin-right:10px;">
        </el-date-picker>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>

    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="条码"  prop="facilityBarcode" align="center"/>
      <el-table-column label="大类"  prop="facilityBarcodeType1" align="center"/>
      <el-table-column label="小类"  prop="facilityBarcodeType2" align="center"/>
      <el-table-column label="规格型号"  prop="facilityBarcodeType3" align="center"/>
      <el-table-column label="名称"  prop="facilityName" align="center"/>
      <el-table-column label="出入状态"  prop="accessType" align="center"/>
      <el-table-column label="工作中心"  prop="workCenter" align="center"/>
      <el-table-column label="借出/归还日期"  prop="accessDate" align="center"/>
      <el-table-column label="借/还人"  prop="accessJobNumber" align="center"/>
      <el-table-column label="当前状态"  prop="type" align="center"/>
      <el-table-column label="位置"  prop="lendingPosition" align="center"/>
      <el-table-column label="管理员"  prop="userName" align="center"/>
      <el-table-column label="记录时间"  prop="createTime" align="center"/>
      <el-table-column label="操作" fixed="right" align="center" width="130">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button
                        icon="el-icon-delete"
                        class="el-button el-button--danger"
                        style="font-size: 15px;"
                        @click="handleDelete(scope.row,scope.$index)"
                    ></el-button>
                </div>
            </template>
      </el-table-column>
      <el-table-column label="使用明细" fixed="right" align="center" width="150">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <el-link :underline="false" size="mini" type="primary" @click="detailAccess(scope.row)">点击打开使用明细</el-link>
                </div>
            </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="使用明细表"
      :visible.sync="showMX"
      @close="showMX = false"
      width="50%"
    >
    <el-table  :data="tableMX" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="工单号"  prop="deviceBarcode" align="center"/>
      <el-table-column label="数量"  prop="completionQuantity" align="center"/>
      <el-table-column label="客户编码"  prop="clientNumber" align="center"/>
      <el-table-column label="工序"  prop="orderType" align="center"/>
      <el-table-column label="工段号"  prop="orderPlanNo" align="center"/>
      <el-table-column label="扫码人员"  prop="jobNumber" align="center"/>
      <el-table-column label="扫码时间"  prop="createTime" align="center"/>
    </el-table>
        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <!-- <el-button @click="showMX = false">取 消</el-button> -->
            <el-button type="primary" @click="showMX = false">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 修改数据弹窗 -->
    <el-dialog
      title="修改"
      :visible.sync="showupd"
      @close="showupd = false"
      width="50%"
    >
        <el-form :model="updForm" ref="updForm" :rules="addRules" label-width="100px">
        <el-row>
            <el-col :span="8">
                <el-form-item label="条码" prop="facilityBarcode" >
                    <el-input placeholder="请扫码或输入资源条码" v-model="updForm.facilityBarcode"/>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="借/归人" prop="accessJobNumber" >
                    <el-select
                        @focus="focusName"
                        filterable
                        v-model="updForm.accessJobNumber">
                        <el-option
                        placeholder="请选择借/归人"
                            v-for="(item,index) in userList"
                            :key="index"
                            :label="item.userName"
                            :value="item.userName">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="借/归状态" prop="accessType">
                    <el-select
                        v-model="updForm.accessType"
                        >
                        <el-option
                        placeholder="请选择借出/归还"
                            v-for="(item,index) in accessTypeList"
                            :key="index"
                            :label="item"
                            :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="8">
                <el-form-item label="借/归日期" prop="accessDate">
                    <el-date-picker
                        v-model="updForm.accessDate"
                        type="datetime"
                        placeholder="选择日期时间"
                        align="right"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        >
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :span="16">
                <el-form-item label="借出位置" prop="lendingPosition">
                    <el-input placeholder="请输入借出位置；（如：整机三线、内部OBA、一楼充电桩线等）" clearable type="textarea" v-model="updForm.lendingPosition"/>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showupd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="updprocess('updForm')"
            >修改</el-button
            >
        </div>
    </el-dialog>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { selfacilityAccess,addfacilityAccess,delfacilityAccess,updfacilityAccess,facilityAccess,selbarcodeType } from "@/api/processRoute"
import { getCenter } from '../../api/workSection.js'
import { findUserListGroup } from '../../api/chargingData.js'
export default {
    name: 'frockInOrOut',
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                facilityBarcode: '',                      //工装条码
                accessJobNumber: ''                         //借出/归还人工号
            },
            total: 0,                                      //数据的总数
            userList:[],
            tableInfo: [],
            tableMX:[],
            showMX: false,
            loadingList: false,
            loading: false,
            centerList: [],                         //工作中心列表
            createForm: {
                accessDate: this.setNowTime()
            },
            dateOptions: this.getNowTime(),
            pickerOptions: {                            // 选择时间范围
              shortcuts: [{
                text: '最近一周',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近一个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近三个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                  picker.$emit('pick', [start, end]);
                }
              }]
            },
            updForm: {},
            props: { multiple: true },
            // 表单校验
            addRules: {
                facilityBarcode: [
                    { required: true, message: "工装条码不能为空!", trigger: "change" },
                ],
                accessJobNumber: [
                    { required: true, message: "借出/归还人工号不能为空!", trigger: "change" },
                ],
                accessDate: [
                    { required: true, message: "借出/归还日期不能为空!", trigger: "change" },
                ],
                accessType: [
                    { required: true, message: "资源出入库状态不能为空!", trigger: "change" },
                ],
            },
            showAdd: false,
            showupd: false,
            userInfo: this.$store.state.user.userInfo,
            barcodeType1List: [],
            accessTypeList: ['借出','归还'],
            barcodeType2List: [],
            barcodeType3List: []
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async focusName(){
            let query = {page:1,limit:9999,status: 1}
            const {data} = await findUserListGroup(query)
            this.userList = data
        },
         //初始默认执行(重点)，返回日期格式YYYY-MM-DD HH:MM:SS
         getNowTime() {
        let dateTime = +new Date()+8*3600*1000
        const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
            .toISOString()
            .replace('T', ' ')
            .split('.')[0]
            // .substring(0,10) //默认开始时间7天前
        const end = new Date(dateTime)
            .toISOString()
            .replace('T', ' ')
            .split('.')[0]
            // .substring(0,10)//默认结束时间当前时间
        console.log([start, end])
        return [start, end]
        },
        async getBarcodeType(type) {
            this.loadingList = true
            let query = {
                facilityBarcodeType: type,
                page: 1,
                limit: 10000
            }
            let data = await selbarcodeType(query)
            let errmsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            if(type == '大类'){
                this.barcodeType1List = data.data.records
            } else if(type == '小类') {
                this.barcodeType2List = data.data.records
            } else if(type == '规格') {
                this.barcodeType3List = data.data.records
            }
            this.loadingList = false
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery,this.param)
            if(this.dateOptions) {
              if(this.dateOptions.length) {
                  query.strTime = this.dateOptions[0]
                  query.endTime = this.dateOptions[1]
              }
            }
            let data = await selfacilityAccess(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            this.total = data.data.count
            this.tableInfo = data.data.list
        },
        handleDelete(row,index) {
            this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delprocess(row,index)
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                })
            })
        },
        async delprocess(row,index){
          let res = await delfacilityAccess({id: row.id})
          if(res.code == '500') return
          if(res.code != '1') return this.$message.error(res.msg)
          this.tableInfo.splice(index,1)
          this.$message.success(res.msg)
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            facilityBarcode: '条码',
            facilityBarcodeType1: '大类',
            facilityBarcodeType2: '小类',
            facilityBarcodeType3: '规格型号',
            facilityName: '名称',
            accessType: '出入状态',
            workCenter: '工作中心',
            accessDate: '借出/归还日期',
            accessJobNumber: '借/还人',
            type: '当前状态',
            lendingPosition: '位置',
            userName: '管理员',
            createTime: '记录时间',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery,this.param)
          query.page = 1
          query.limit = 10000
            if(this.dateOptions) {
              if(this.dateOptions.length) {
                  query.strTime = this.dateOptions[0]
                  query.endTime = this.dateOptions[1]
              }
            }
          let arr = await selfacilityAccess(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.list.length){
            this.loading = false
            this.$message.error('暂无数据')
          }
          const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '工装出入库', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              facilityBarcode: item.facilityBarcode,
              facilityBarcodeType1: item.facilityBarcodeType1,
              facilityBarcodeType2: item.facilityBarcodeType2,
              facilityBarcodeType3: item.facilityBarcodeType3,
              facilityName: item.facilityName,
              accessType: item.accessType,
              workCenter: item.workCenter,
              accessDate: item.accessDate,
              accessJobNumber: item.accessJobNumber,
              type: item.type,
              lendingPosition: item.lendingPosition,
              userName: item.userName,
              createTime: item.createTime,
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {
                facilityBarcode: '',                      //工装条码
                accessJobNumber: '',                         //借出/归还人工号
                accessType: ''
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        // 提交表单之前先进行验证
        addfacility(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitprocess()
                } else {
                    return false
                }
            })
        },
        async submitprocess(){
            let query = Object.assign({},this.createForm)
            const data = await addfacilityAccess(query)
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.resetForm()
            this.showAdd = false
            this.handleFilter()
        },
        resetForm(){
             this.$refs.createForm.resetFields();
        },
        handleEdit(row){
            this.updForm = Object.assign({},row)
            this.showupd = true
        },
        // 点击明细
        async detailAccess(row){
            let query = {
                emsFacilityAccessId: row.id,
                page: 1,
                limit: 10000
            }
            const res = await facilityAccess(query)
            console.log(res)
            if(res.data.list && res.data.list.length){
                this.tableMX = res.data.list
            }
            this.showMX = true
        },
        // 提交表单之前先进行验证
        updprocess(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.updfacilityAccess()
                } else {
                    return false
                }
            })
        },
        async updfacilityAccess(){
            let query = Object.assign({},this.updForm)
            console.log(this.updForm,query)
            const data = await updfacilityAccess(query)
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.showupd = false
            this.handleFilter()
            this.$message.success(errMsg)
        },
        addInOrOut(){
            this.showAdd = true
            this.createForm.accessDate = this.setNowTime()
        },
        setNowTime() {
            let date = new Date()
            // 获取年、月、日、时、分、秒  
            const year = date.getFullYear();  
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的  
            const day = String(date.getDate()).padStart(2, '0');  
            const hour = String(date.getHours()).padStart(2, '0');  
            const minute = String(date.getMinutes()).padStart(2, '0');  
            const second = String(date.getSeconds()).padStart(2, '0');  
            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;   
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>
